#include "head.h"

//服务器gets处理逻辑
bool my_gets(sendMsg msg,client_status *user,int net_fd)
{
    printf("my_gets服务端进入处理.\n");
    MYSQL_RES* result0;
    MYSQL_ROW row;
    recvMsg ret_msg;
    bzero(&ret_msg,sizeof(ret_msg));
    //接收路径
    char full_path[50]={0};
    strcpy(full_path,msg.msg);
    printf("full_path:%s\n",full_path);

    int ishere=0;
    //查询出所有文件的路径
    mysql_query(user->sql,"SELECT path FROM files where file_type=2");
    //获取查询结果集
    result0 = mysql_store_result(user->sql);
    while ((row = mysql_fetch_row(result0))) {
        printf("row:%s\n",row[0]);
        if(strcmp(row[0],full_path)==0){
            ishere=1;
            printf("ishere:%d\n",ishere);
            break;//只要知道路径存在就可以了
                  //只要有一条路径重复,就说明这条路径存在
        }
    }
    printf("ishere:%d\n",ishere);

    //发送错误信号
    if(ishere==0){
        printf("ishere:%d\n",ishere);
        strcpy(ret_msg.statu,"nopath");
        //发送错误信号
        send(net_fd,&ret_msg,sizeof(ret_msg),MSG_NOSIGNAL);
        mysql_free_result(result0);
        return false;
    }else{
        printf("ishere:%d\n",ishere);
        strcpy(ret_msg.statu,"path");
        //发送错误信号
        send(net_fd,&ret_msg,sizeof(ret_msg),MSG_NOSIGNAL);
    }
    printf("ret_msg:%s\n",ret_msg.statu);

    mysql_free_result(result0);

    //接收文件名和文件名长度
    //int file_name_len;
    //char document_name[1024];
    //recv(net_fd,&file_name_len,sizeof(int),MSG_WAITALL);
    //recv(net_fd,document_name,file_name_len,MSG_WAITALL);

    //printf("f_name:%s\n",document_name);

    MYSQL_RES* result;

    //得到存储在serve端的文件真名
    char query[160]={0};
    snprintf(query, sizeof(query), "select hash from files where path='%s'", full_path);
    mysql_query(user->sql, query);
    result = mysql_store_result(user->sql);
    row = mysql_fetch_row(result);
    char real_fname[255]={0};
    strcpy(real_fname, row[0]);
    printf("real_fname:%s\n", real_fname);
    //由真名拼接出真路径，为后续打开 文件备用
    char real_path[255]={0};
    getcwd(real_path,sizeof(real_path));
    strcat(real_path,"/");
    strcat(real_path,real_fname);
    printf("real_path:%s\n", real_path);

    mysql_free_result(result);


    //来开文件了
    int file_fd = open(real_path, O_RDWR);
    //if(file_fd<0){
    //  strcpy(ret_msg.statu,"nofile");
    //     send(net_fd, &ret_msg, sizeof(ret_msg), MSG_NOSIGNAL);
    // }


    //从客户端获取偏移量
    off_t offset = 0;
    int ret = recv(net_fd,&offset,sizeof(offset),MSG_WAITALL);

    printf("offset  %ld\n",offset);
    printf("%d\n", ret);

    //获取真实文件大小
    struct stat st;
    fstat(file_fd, &st);
    //发送文件大小给客户端
    send(net_fd,&st.st_size,sizeof(st.st_size),MSG_NOSIGNAL);


    // 使用 sendfile 从偏移量继续发送文件内容
    //    sendfile(net_fd, file_fd, &offset,40960);
    sendfile(net_fd, file_fd, &offset,st.st_size);

    close(file_fd);
    printf("my_gets服务端完成\n");
    return true;
}
